﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Gui.CompletionWindow;
using System.Windows.Forms;
using ICSharpCode.MSSQLExtensions.SqlParser;


namespace ICSharpCode.MSSQLExtensions
{

    public class HCSqlCodeCompletionProvider : ICompletionDataProvider
    {
        private System.Windows.Forms.ImageList m_ImageList = new ImageList();
        //private DBSourceToolsLib.Suggestions.SuggestionBuilder m_SuggestionBuilder;
        private SenseBuilder m_SenseBuilder;
        public HCSqlCodeCompletionProvider(Form oForm, SenseBuilder oBuilder)
        {
            m_SenseBuilder = oBuilder;
            m_ImageList.Images.Add(Properties.Resources.DBIcon_field);
            m_ImageList.Images.Add(Properties.Resources.DBIcon_table);
            m_ImageList.Images.Add(Properties.Resources.DBIcon_view);
        }
        public System.Windows.Forms.ImageList ImageList
        {
            get { return m_ImageList; }
        }

        public string PreSelection
        {
            get { return null; }
        }

        public int DefaultIndex
        {
            get { return -1; }
        }

        public CompletionDataProviderKeyResult ProcessKey(char key)
        {
            if (char.IsLetterOrDigit(key) || key == '*' || key == '.')
            {
                return CompletionDataProviderKeyResult.NormalKey;
            }
            else
            {
                // key triggers insertion of selected items
                return CompletionDataProviderKeyResult.InsertionKey;
            }

        }

        /// <summary>
        /// Called when entry should be inserted. Forward to the insertion action of the completion data.
        /// </summary>
        public bool InsertAction(ICompletionData data, TextArea textArea, int insertionOffset, char key)
        {
            textArea.Caret.Position = textArea.Document.OffsetToPosition(insertionOffset);
            return data.InsertAction(textArea, key);

        }

        public ICompletionData[] GenerateCompletionData(string fileName, TextArea textArea, char charTyped)
        {
            // We can return code-completion items like this:
            List<ICompletionData> oList = new List<ICompletionData>();
            foreach (DBSourceToolsLib.Suggestions.Suggestion oSuggestion in m_SenseBuilder.GetSuggestionsForCursorAt(textArea.Caret.Offset))
            {
                oList.Add(new DefaultCompletionData(oSuggestion.Name, oSuggestion.Description, oSuggestion.ImageIdx));
            }

            return oList.ToArray();
        }

    }

}
